package com.ynkbny.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynkbny.domain.Device;
import com.ynkbny.domain.excel.MeterReadingExportVO;
import com.ynkbny.domain.pojo.*;
import com.ynkbny.lgapi.*;
import com.ynkbny.mapper.DeviceMapper;
import com.ynkbny.mapper.ProjectMapper;
import com.ynkbny.mapper.RegionMapper;
import com.ynkbny.service.DeviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 设备表-表服务实现类
 *
 * @author : juzipi123
 * @date : 2023-7-25
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {
    private static final Logger log = LoggerFactory.getLogger(DeviceServiceImpl.class);
    @Resource
    HistoryData historyData;
    @Resource
    YnBk ynBk;

    @Resource
    private User user;
    @Resource
    private Project project;
    @Resource
    private Region region;
    @Resource
    private com.ynkbny.lgapi.Device device;
    @Resource
    DeviceMapper mapper;

    @Resource
    private ProjectMapper projectMapper;

    @Resource
    private RegionMapper regionMapper;

    @Resource
    private DeviceMapper deviceMapper;
    // 定义一个静态字符串数组
    public static final String[] STRING_ARRAY = {"总降 锡-＃1火法精炼电源0111", "总降 锡-硫酸1＃电源0107",
            "总降 锡-烟尘＃1电源0105", "总降 锡-2＃火法精炼线0317","总降 锡-2#锌回收线0307","总降 锡-2#硫酸线0303",
    "总降 锡-2#熔炼线0305","总降 锡-2#氧气站0318","总降 锡-1＃熔炼电源0106","总降 锡-1＃氧气站电源0115","总降 铜-＃2电炉0208",
    "总降 铜-＃2氧气站电源0209","总降 铜-＃1氧气站0110","总降 铜-电极锅炉0114","总降 铜-1＃铜熔炼0108","总降 铜-1＃硫酸0112",
            "总降 铜-1＃电解0113","总降 铜-1＃电炉0109","总降 铜-10kV#2电解0213","总降 铜-10kV ＃2硫酸0211","总降 铜-10kV #2熔炼0207",
    "总降 危废渣场0206","总降 化工有机锡0101"};


    /**
     * 构建设备树结构
     *
     * @param projId 项目id
     * @return JSONObject对象
     * @author : YY
     */
    @Override
    public JSONObject buildDeviceTree(long projId) {
        log.info("入参：{}", projId);

        // 获取token
        JSONObject loginResult = user.login("ybbky", "123456");
        log.info(loginResult.toJSONString());
        String token = loginResult.getString("data");

        //调用项目接口
        JSONObject projectJson = project.queryProject(token, projId);
        //调用区域接口
        JSONObject regionJson = region.queryRegionByProject(token, projId);
        //调用设备接口
        JSONObject deviceJson = device.queryDeviceByProject(token, projId);

        //创建JSONObject
        JSONObject jsonObject = new JSONObject();
        // 获取项目信息
        jsonObject.put("name", projectJson.getJSONObject("data").getString("name"));
        jsonObject.put("id", projectJson.getJSONObject("data").getString("id"));
        // 获取区域信息
        JSONArray jsonArray = regionJson.getJSONArray("data");
        jsonObject.put("region", jsonArray);
        // 获取设备信息
        JSONArray deviceJsonArray = deviceJson.getJSONArray("data");
        // 按区域id分组
        HashMap<String, JSONArray> deviceMap = new HashMap<>();
        for (Object entity : deviceJsonArray) {
            JSONObject entityJson = (JSONObject) JSON.toJSON(entity);
            String regionId = entityJson.getString("regionId");
            if (!deviceMap.containsKey(regionId)) {
                deviceMap.put(regionId, new JSONArray());
            }
            deviceMap.get(regionId).add(entity);
        }
        //添加散点
        jsonObject.put("device", deviceMap.get(null));
        // 按区域id填充
        jsonArray.forEach(n -> {
            JSONObject tempJson = (JSONObject) JSON.toJSON(n);
            tempJson.put("device", deviceMap.get(tempJson.getString("id")));
        });
        log.info("方法返回值：{}", jsonObject);

        return jsonObject;
    }

    @Override
    public List<RegionTreeVO> buildRegionDeviceTree(long projId) {
        log.info("入参：{}", projId);

        // 获取token
        JSONObject loginResult = user.login("ybbky", "123456");
        log.info(loginResult.toJSONString());
        String token = loginResult.getString("data");
        //调用区域接口
        JSONArray regionJson = (region.queryRegionByProject(token, projId)).getJSONArray("data");
        //调用设备接口
        JSONArray deviceJson = (device.queryDeviceByProject(token, projId)).getJSONArray("data");
        //创建JSONObject
        JSONObject jsonObject = new JSONObject();
        List<RegionTreeVO> list = new ArrayList<>();
        for (int i = 0; i < regionJson.size(); i++) {
            RegionTreeVO regionTreeVO = new RegionTreeVO();
            JSONObject object = ((JSONObject) regionJson.get(i));
            String regionId = object.getString("id");
            regionTreeVO.setId(object.getString("id"));
            List<RegionTreeVO> childrenList = new ArrayList<>();
            for (int j = 0; j < deviceJson.size(); j++) {
                JSONObject object1 = ((JSONObject) deviceJson.get(j));
                if (regionId.equals(object1.get("regionId").toString())) {
                    RegionTreeVO treeVO = new RegionTreeVO();
                    treeVO.setLabel(object1.get("name").toString());
                    treeVO.setId(object1.get("id").toString());

                    childrenList.add(treeVO);
                }
            }
            regionTreeVO.setLabel(object.getString("name"));
            regionTreeVO.setChildren(childrenList);
            list.add(regionTreeVO);
        }
        return list;
    }

    @Override
    public DeviceExcelDataVO getDeviceByTime(String name,String deviceId, String startTime, String endTIme,String meteic) {
        String token = (ynBk.login("ybbky", "123456", false).getString("data")).toString();
        JSONObject jsonObject = historyData.getDataForLaoGou(token,deviceId,startTime,endTIme,meteic)
                .getJSONObject("data");
        JSONArray jsonArray = jsonObject.getJSONArray("v1");
        if(jsonArray.size() != 0){
            JSONObject startObject = (JSONObject) jsonArray.get(0);
            JSONObject endObject = (JSONObject) jsonArray.get(jsonArray.size()-1);
            BigDecimal startValue = new BigDecimal(startObject.get(meteic).toString());
            BigDecimal endValue = new BigDecimal(endObject.get(meteic).toString());
            BigDecimal value = endValue.subtract(startValue);
            System.out.println(startValue);
            DeviceExcelDataVO deviceExcelDataVO = new DeviceExcelDataVO();
            deviceExcelDataVO.setDeviceName(name);
            deviceExcelDataVO.setStartData(startValue);
            deviceExcelDataVO.setEndData(endValue);
            deviceExcelDataVO.setValue(value);
            deviceExcelDataVO.setUnit("kwH");
            return deviceExcelDataVO;
        }else{
            DeviceExcelDataVO deviceExcelDataVO = new DeviceExcelDataVO();
            deviceExcelDataVO.setDeviceName(name);
            deviceExcelDataVO.setStartData(new BigDecimal(0));
            deviceExcelDataVO.setEndData(new BigDecimal(0));
            deviceExcelDataVO.setValue(new BigDecimal(0));
            deviceExcelDataVO.setUnit("kwH");
            return deviceExcelDataVO;
        }
    }

    @Override
    public MeterReadingExportVO getDeviceReadingByTime(String name, String deviceId, String startTime, String endTIme, String metric) {
        String token = (ynBk.login("ybbky", "123456", false).getString("data")).toString();
        JSONObject jsonObject = historyData.getDataForLaoGou(token,deviceId,startTime,endTIme,metric)
                .getJSONObject("data");
        JSONArray jsonArray = jsonObject.getJSONArray("v1");
        if(jsonArray.size() != 0){
            //0点
            JSONObject startObject = (JSONObject) jsonArray.get(0);
            //7点
            JSONObject sevenObject = (JSONObject) jsonArray.get(13);
            //9
            JSONObject ninObject = (JSONObject) jsonArray.get(17);
            JSONObject tenObject = (JSONObject) jsonArray.get(19);
            JSONObject elevenObject = (JSONObject) jsonArray.get(21);
            JSONObject teObject = (JSONObject) jsonArray.get(22);
            JSONObject fiveObject = (JSONObject) jsonArray.get(32);
            JSONObject fivebanObject = (JSONObject) jsonArray.get(33);
            JSONObject sixbanObject = (JSONObject) jsonArray.get(35);
            JSONObject ttbanObject = (JSONObject) jsonArray.get(42);
            JSONObject ershisanObject = (JSONObject) jsonArray.get(45);
            MeterReadingExportVO deviceExcelDataVO = new MeterReadingExportVO();
            deviceExcelDataVO.setName(name);
            deviceExcelDataVO.setZero(new BigDecimal(startObject.get(metric).toString()));
            deviceExcelDataVO.setSeven(new BigDecimal(sevenObject.get(metric).toString()));
            deviceExcelDataVO.setNine(new BigDecimal(ninObject.get(metric).toString()));
            deviceExcelDataVO.setTen(new BigDecimal(tenObject.get(metric).toString()));
            deviceExcelDataVO.setEleven(new BigDecimal(elevenObject.get(metric).toString()));
            deviceExcelDataVO.setTwle(new BigDecimal(teObject.get(metric).toString()));
            deviceExcelDataVO.setShiqi(new BigDecimal(fiveObject.get(metric).toString()));
            deviceExcelDataVO.setShiqiban(new BigDecimal(fivebanObject.get(metric).toString()));
            deviceExcelDataVO.setShibaban(new BigDecimal(sixbanObject.get(metric).toString()));
            deviceExcelDataVO.setErshier(new BigDecimal(ttbanObject.get(metric).toString()));
            deviceExcelDataVO.setErshisan(new BigDecimal(ershisanObject.get(metric).toString()));
            return deviceExcelDataVO;
        }else{
            MeterReadingExportVO deviceExcelDataVO = new MeterReadingExportVO();
            return deviceExcelDataVO;
        }
    }

    /**
     * @param projId 项目id
     * @author : juzipi123
     */
    @Override
    public void delByProjId(Long projId) {
        log.info("入参：{}", projId);
        mapper.delByProjId(projId);
    }

    /**
     * @author : juzipi123
     */
    @Override
    public void del() {
        mapper.del();
    }

    /**
     * @param projId 项目id
     * @return
     * @author : juzipi123
     */
    @Override
    public List<String> selectByprojId(Long projId) {
        log.info("入参：{}", projId);
        List<String> strings = mapper.selectByprojId(projId);
        log.info("方法返回值：{}", strings);
        return strings;
    }

    /**
     * @param projId 项目id
     * @return
     * @author : juzipi123
     */
    @Override
    public TreeProjDeviceVO treeProjDevice(String projId) {
        log.info("入参：{}", projId);

        TreeProjDeviceVO treeProjDeviceVO = new TreeProjDeviceVO();

        //1.查询（项目表）取项目名
        com.ynkbny.domain.Project project = projectMapper.selectById(projId);
        ProjectVO projectVO = new ProjectVO();
        projectVO.setId(projId);
        projectVO.setName(project.getName());

        HashMap<String, Object> map2 = new HashMap<>();

        //2.查询 （设备表）取设备 id,名字,区域id
        List<Device> devices = deviceMapper.selectByprojId2(projId);
        Map<String, List<Device>> regionMap = devices.stream().collect(Collectors.groupingBy(Device::getRegionId));

        ArrayList<DeviceTypeVO> deviceTypeVOList = new ArrayList<>();
        List<RegionVO> regionVOS = new ArrayList<>();
        for (Map.Entry<String, List<Device>> entry : regionMap.entrySet()) {

            // 如果区域id不为 null
            if (!entry.getKey().equals("null")) {
                RegionVO regionVO = new RegionVO();
                com.ynkbny.domain.Region region = regionMapper.selectByprojIdAndRegionId(projId, entry.getKey());

                regionVO.setRegionId(region.getRegionId());
                regionVO.setRegionName(region.getRegionName());

                ArrayList<DeviceTypeVO> deviceTypeVOS = new ArrayList<>();
                List<Device> deviceList = entry.getValue();
                Map<String, List<Device>> deTypeList = deviceList.stream().collect(Collectors.groupingBy(Device::getDeviceTypeId));
                for (Map.Entry<String, List<Device>> listEntry : deTypeList.entrySet()) {
                    String key = listEntry.getKey();
                    List<Device> values = listEntry.getValue();

                    DeviceTypeVO deviceTypeVO = new DeviceTypeVO();
                    deviceTypeVO.setDeviceTypeId(key);
                    deviceTypeVO.setDeviceTypeName(values.get(0).getDeviceTypeName());
                    deviceTypeVO.setDeviceList(values);
                    deviceTypeVOS.add(deviceTypeVO);
                }

                regionVO.setDeviceTypeVO(deviceTypeVOS);

                regionVOS.add(regionVO);
            } else {
                List<Device> deviceList = entry.getValue();
                Map<String, List<Device>> deTypeList = deviceList.stream().collect(Collectors.groupingBy(Device::getDeviceTypeId));
                for (Map.Entry<String, List<Device>> listEntry : deTypeList.entrySet()) {
                    String key = listEntry.getKey();
                    List<Device> values = listEntry.getValue();

                    DeviceTypeVO deviceTypeVO = new DeviceTypeVO();
                    deviceTypeVO.setDeviceTypeId(key);
                    deviceTypeVO.setDeviceTypeName(values.get(0).getDeviceTypeName());
                    deviceTypeVO.setDeviceList(values);
                    deviceTypeVOList.add(deviceTypeVO);
                }
            }
        }

        projectVO.setRegionVOList(regionVOS);
        treeProjDeviceVO.setProjectVO(projectVO);
        treeProjDeviceVO.setDeviceTypeVOList(deviceTypeVOList);

        log.info("方法返回值：{}", treeProjDeviceVO);
        return treeProjDeviceVO;
    }

    /**
     * 根据设备id查询
     *
     * @param deviceId 设备id
     * @return 结果
     * @author : juzipi123
     */
    @Override
    public Device selectByDeviceId(String deviceId) {
        log.info("入参：{}", deviceId);
        Device device = mapper.selectByDeviceId(deviceId);
        log.info("方法返回值：{}", device);
        return device;
    }

    @Override
    public List<Device> getDeviceListByRegionId(String regionId) {
        Device device1 = new Device();
        return null;
    }

    /**
     * 根据设备id删除
     *
     * @param deviceId 设备id
     * @author : juzipi123
     */
    @Override
    public void delByDeviceId(String deviceId) {
        log.info("入参：{}", deviceId);
        mapper.delByDeviceId(deviceId);
        log.info("方法返回值：无");
    }
    public List<MeterReadingExportVO> getDataList(long projId, String startTime,String endTime){
        log.info("入参：{}", projId);

        // 获取token
        JSONObject loginResult = user.login("ybbky", "123456");
        log.info(loginResult.toJSONString());
        String token = loginResult.getString("data");
        //调用区域接口
        JSONArray regionJson = (region.queryRegionByProject(token, projId)).getJSONArray("data");
        //调用设备接口
        JSONArray deviceJson = (device.queryDeviceByProject(token, projId)).getJSONArray("data");
        //创建JSONObject
        JSONObject jsonObject = new JSONObject();
        List<RegionTreeVO> list = new ArrayList<>();
        List<MeterReadingExportVO> deviceMapperList = new ArrayList<>();
        for (int i = 0; i < regionJson.size(); i++) {
            RegionTreeVO regionTreeVO = new RegionTreeVO();
            JSONObject object = ((JSONObject) regionJson.get(i));
            String regionId = object.getString("id");
            regionTreeVO.setId(object.getString("id"));
            List<RegionTreeVO> childrenList = new ArrayList<>();
            for (int j = 0; j < deviceJson.size(); j++) {
                JSONObject object1 = ((JSONObject) deviceJson.get(j));
                if (regionId.equals(object1.get("regionId").toString())) {
                    RegionTreeVO treeVO = new RegionTreeVO();
                    treeVO.setLabel(object1.get("name").toString());
                    treeVO.setId(object1.get("id").toString());
                    MeterReadingExportVO vo = getDeviceReadingByTime(object1.get("name").toString(),object1.get("id").toString(),startTime,endTime,"14068");
                    for(int k = 0; k < STRING_ARRAY.length; k++){
                        if (object1.get("name").equals(STRING_ARRAY[k])){
                            childrenList.add(treeVO);
                            deviceMapperList.add(vo);
                        }
                    }
                }
            }
            regionTreeVO.setLabel(object.getString("name"));
            regionTreeVO.setChildren(childrenList);
            list.add(regionTreeVO);
        }
        return deviceMapperList;
    }

}